package com.hue.concurrent.day02;

/*
    售票问题的线程安全问题
 */
public class Demo03 {
    public static void main(String[] args) {
        TicketWindow ticketWindow = new TicketWindow(5000);

        for (int i = 0; i < 2000; i++) {
            new Thread(() -> {
                ticketWindow.sale();
            }).start();
        }

        while (Thread.activeCount() > 2) {
            Thread.yield();
        }

        System.out.println("余票:" + ticketWindow.getTicketCount());
    }

}

class TicketWindow {
    private int ticketCount;

    public TicketWindow(int ticketCount) {
        this.ticketCount = ticketCount;
    }

    public int getTicketCount() {
        return this.ticketCount;
    }

    public synchronized void sale() {
        if (ticketCount > 0) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ticketCount--;
        }
    }
}
